import { getToken, removeToken, setToken } from '@/utils/auth'
import { getInfo, getMoreInfo, login } from '../../api/user'
const state = () => {
  return {
    // token
    token: getToken(),
    // 用户信息
    userInfo: {}
  }
}

const mutations = {
  // 修改token
  setToken(state, newToken) {
    state.token = newToken
  },
  // 修改用户信息
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  }
}

const actions = {
  // actions的login
  async login(context, data) {
    // 接口的login
    const token = await login(data)

    // 把token存入仓库
    context.commit('setToken', token)
    // 把token存入本地
    setToken(token)
  },
  async getUserInfo(context) {
    const res = await getInfo()
    console.log(res)
    // context.commit('setUserInfo', res)
    const moreRse = await getMoreInfo({ id: res.userId })
    console.log(moreRse)
    context.commit('setUserInfo', { ...res, ...moreRse })
  },
  // 用户登出
  logout(context) {
    // 删除本地token
    removeToken()
    // 删除仓库token
    context.commit('setToken', undefined)
    // 删除用户信息
    context.commit('setUserInfo', {})
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
